<template>
	<view class="login-form">
		<up-form labelWidth="60px" labelPosition="left" :model="formData" :rules="rules" ref="formRef">
			<up-form-item required label="手机号" prop="phone" borderBottom>
				<up-input v-model="formData.phone" placeholder="请输入手机号">
					<template #suffix>
						<up-code ref="uCodeRef" @change="codeChange" seconds="20" changeText="X秒后重新获取"></up-code>
						<up-button @tap="getCode" :text="tips" type="success" size="mini"></up-button>
					</template>
				</up-input>
			</up-form-item>
			<up-form-item required prop="code" label="验证码" borderBottom>
				<up-input placeholder="请输入内容" border="surround" v-model="formData.code"></up-input>
			</up-form-item>
		</up-form>
		<up-button @click="submit">登录</up-button>
	</view>
</template>

<script setup>
	import { GET_PHONE_CODE,PHONE_LOGIN } from '../../api/login';
import { ref } from 'vue';
const formRef = ref(null)
const uCodeRef = ref(null)
const tips = ref('')
	const formData = ref({
		phone: '',
		code: ''
	})
	const rules = ref({
		phone: {
			type: 'string',
			required: true,
			message: '请输入手机号',
			trigger: ['change', 'blur']
		},
		code: {
			type: 'string',
			required: true,
			message: '请输入验证码',
			trigger: ['change', 'blur']
		}
	})
	const codeChange = (text) => {
		tips.value = text
	}
	const getCode = () => {
		if(!formData.value.phone) {
			uni.$u.toast('请输入手机号获取验证码')
			return
		}
		GET_PHONE_CODE().then(res => {
			console.log(res)
			uni.setStorageSync('code', res.code)
			uCodeRef.value.start()
		})
	}
	const submit = () => {
		// 点击登录按钮做两个校验：
		// 1.必填校验
		// 2.填写的验证码与接口返回的验证码(接口返回的验证码咱们存到storage中)是否一致
		formRef.value.validate().then(valid => {
			if(valid){
				const code = uni.getStorageSync('code')
				if(code===formData.value.code) {
					// 去登陆吧
					PHONE_LOGIN(formData.value.phone).then(res => {
						console.log(res)
						uni.setStorageSync('token', res.token.token)
						uni.switchTab({
							url:'/pages/my/my'
						})
					})
				} else {
					uni.$u.toast('验证码输入错误')
				}
			}
		})
		
	}
</script>

<style lang="scss">
	.login-form {
		width: 80vw;
		margin: 0 auto;
	}
</style>